package xlog

import (
	"encoding/json"
	"fmt"
	"gitee.com/hjb0924/x-go/xtime"
	"os"
	"strings"
	"time"
)

type logConfig struct {
	SubPath  string
	FileName string
	//SplitPath string
}

func New() *logConfig {
	return &logConfig{
		SubPath:  "default",
		FileName: "log",
	}
}

func (this *logConfig) SetSubPath(subPath string) *logConfig {
	this.SubPath = subPath
	return this
}

func (this *logConfig) SetFileName(fileName string) *logConfig {
	this.FileName = fileName
	return this
}

func (this *logConfig) Push(content ...interface{}) {

	ds := "/"

	var path = "./runtime/" + strings.Trim(this.SubPath, ds) + "/" +
		time.Now().Format("2006-01/") + time.Now().Format("02")

	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			os.MkdirAll(path, os.ModePerm)
		}
	}

	path += "/" + this.FileName + ".log"
	if f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm); err == nil {
		defer func() {
			f.Close()
		}()

		f.WriteString("=============" + time.Now().Format(xtime.FORMAT_DATE_TIME) + "===========\n")

		for _, item := range content {

			switch item.(type) {
			case string, float64, float32, int, int32, int64, uint, uint32, uint64, bool:
				f.WriteString(fmt.Sprint(item))
			case []byte:
				f.WriteString(string(item.([]byte)))
			case map[string]interface{}:
				b, _ := json.Marshal(item)
				f.WriteString(string(b))
			case interface{}:
				b, _ := json.Marshal(item)
				f.WriteString(string(b))
			default:
				f.WriteString(fmt.Sprint(item))
			}

			f.WriteString("\n")
		}
		f.WriteString("\n")
	}

}
